package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户粉丝信息表 服务实现类
 * </p>
 *
 * @author QLJ
 * @since 2022-08-29
 */
@Service
@RefreshScope //naocs参数热更新
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Value("${leadnews.jwt.expire}")
    private int expire;

    /**
     * 用户登录
     */
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto loginDto) {
        //登录用户手机号密码
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();

        //判断是否是游客
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)) {
            //查询条件
            QueryWrapper<ApUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            //从数据库查询用户
            ApUser loginUser = getOne(wrapper);
            //判断账号否存在
            if (loginUser ==null){
                throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            //登录校验密码
            boolean logState = BCrypt.checkpw(password,loginUser.getPassword());
            if (!logState) {
                throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
//                throw new RuntimeException("账号密码错误登陆失败");
            }

            //生成JWT token
            try {
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
                //将用户密码抹除
                loginUser.setPassword(null);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

                HashMap<Object, Object> loginMap = new HashMap<>();
                loginMap.put("token", token);
                loginMap.put("user", loginUser);
                //返回jwt给前端
                return ResponseResult.okResult(loginMap);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

        } else {
            //游客状态
            ApUser loginUser = new ApUser();
            loginUser.setId(0);

            //生成JWT token
            try {
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);

                HashMap<Object, Object> loginMap = new HashMap<>();
                loginMap.put("token", token);
                //返回jwt给前端
                return ResponseResult.okResult(loginMap);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
